import { h, Component } from 'preact';

import { connect } from 'preact-redux';
import { bindActionCreators } from 'redux';
import { setRuntimeVariable } from '~/actions/user';
import {parse} from 'query-string';


import Loading from '~/components/Loading';
import Modal from '~/components/Modal';
import validate from '~/core/utils/validate';
import { login, saveAddress } from '~/servicer/index.js';
import s from './scss';
import {prize, authUrl} from '~/config';

const {getPrize, losingPrize} = prize;

class Luck extends Component {
	constructor(props) {
		super(props);
		this.state = {
			prizeInfo: null,
			prizeImg: null,
			name: null,
			phone: null,
			address: null,
			secretCode: null,
			displayAddress: false,
			error: {},
			showName: null
		};
	}

	componentWillMount() {
		const {code, state} = parse(window.location.search);
		this.props.setStore({
			value: "code",
			code: code || this.props.code
		});
		this.props.setStore({
			value: "state",
			code: state || this.props.state
		});

		this.login(code || this.props.code, state || this.props.state);
	}

	login = (code, state) => {
		if (!code || !state) {
			this.reEnter();
		}
		Loading.show();
		login({code, state}).then(res => {
			Loading.hide();
			if (res.status === '0') {
				const data = {
					lucky: res.body.lucky || {},
					address: res.body.address || {},
					user: res.body.user || {},
					secretCode: res.body.secretCode
				};

				const { prize1, prize2, prize3, prize4} = prize.getPrize.img;
				const prizeInfo = data.lucky.prizeInfo || '';
				const prizeTitle = prizeInfo.split('#')[0];
				const prizeType = prizeInfo.split('#')[1];
				let prizeImg;
				switch (prizeType) {
					case '1':
						prizeImg = prize1;
						break;
					case '2':
						prizeImg = prize2;
						break;
					case '3':
						prizeImg = prize3;
						break;
					default:
						prizeImg = prize4;
						break;
				}

				this.setState({
					prizeInfo: prizeTitle,
					prizeImg,
					name: data.address.name,
					phone: data.address.phone,
					address: data.address.address,
					secretCode: data.secretCode,
					showName: data.user.name
				});
			}
			if (res.status === '-2') {
				this.reEnter();
			}
			console.log(res);
		}).catch(err => {
			Loading.hide();
			console.log(err);
		});
	}

	reEnter = () => {
		window.location.href = authUrl;
	}

	handleWxts = () => {
		if (this.state.phone || this.state.address || this.state.name) {
			this.handleShowAddress();
			return;
		}
		this.setState({
			error: {
				title: '温馨提示',
				error: '晚会现场人员请不要填写'
			}
		});
	}

	handleShowAddress = () => {
		this.setState({
			displayAddress: true
		});
	}

	handleHideAddress = () => {
		this.setState({
			error: {
				title: null,
				error: null
			}
		}, () => {
			setTimeout(() => {
				this.setState({
					displayAddress: false
				});
			});
		});

	}

	saveAddress = () => {
		const { name, phone, address } = this.state;

		const error = validate({
			VRequire_name: [name, '请输入收件人姓名'],
			VPhone: [phone, '请输入正确手机号码', 'strict'],
			VRequire_address: [address, '请输入收件地址']
		});

		if (error) {
			this.setState({
				error: {
					error,
					title: ''
				}
			});
			return;
		}
		Loading.show();
		saveAddress({
			name,
			phone,
			address
		}, {
			secretCode: this.state.secretCode
		}).then(res => {
			Loading.hide();
			const {status} = res;
			if (status === '0') {
				this.handleHideAddress();
				this.setState({
					error: {
						title: '保存成功',
						error: '您的地址已保存！'
					}
				});
				return;
			}

			if (status === '-2') {
				this.setState({
					secretCode: null
				});
			}

			this.setState({
				error: {
					title: '对不起',
					error: res.errorMsg
				}
			});
			console.log(res);

		}).catch(() => {
			Loading.hide();
		});
	}

	handleAddress = (e) => {
		const data = e.target.value || '';

		this.setState({
			address: data.replace(/\s+/g,"")
		});
	}

	handleTel = (e) => {
		this.setState({
			phone: e.target.value
		});
	}

	handleName = (e) => {
		this.setState({
			name: e.target.value
		});
	}
	closeErr = () => {
		this.setState({
			error: {
				title: null,
				error: null
			}
		});
	}

	handleXianchang = () => {
		this.closeErr();
		this.handleShowAddress();
	}

	render() {
		const { secretCode, prizeInfo, displayAddress, prizeImg } = this.state;
		return (
			<div className={s.root}>
				<div className={s.main}>
					<div className={s.logo} />
					{
						secretCode ?
							<div>
								{prizeInfo ? <div>
									<h4 class="al-c pdt4 fw-n white">
										{getPrize.text(this.state.showName)}
									</h4>
									<h4 class="al-c fw-n pdb2 white">{this.state.prizeInfo || ''}</h4>
									<div className={s.prize} style={{'background-image': `url(${prizeImg})`}}>&nbsp;</div>
									{
										!displayAddress ?
											<div class="al-c pdt3">
												<div className={s.btn} onClick={this.handleWxts} />
											</div> :
											<div className={`formBox w9 center pdt2 ${s.formbox}`}>
												<div class="clearfix pdb2">
													<div className={s.titlab}>
														收件人姓名：
													</div>
													<div>
														<input type="text" value={this.state.name} placeholder="请填写本人姓名" onChange={this.handleName}  />
													</div>
													<div className={s.titlab}>
														收件人手机：
													</div>
													<div>
														<input type="tel" maxLength="11" value={this.state.phone} onChange={this.handleTel} />
													</div>
													<div className={s.titlab}>
														收件人地址：
													</div>
													<div>
														<textarea className={s.textA} onChange={this.handleAddress}>{this.state.address}</textarea>
													</div>
													<div class="al-c mgt1">
														<button style={{width:'40%'}} onClick={this.saveAddress} class={`${s.errorbtn} ${s.errorbtnfirst}`}>确定</button> &nbsp;&nbsp;&nbsp;&nbsp;
														<button style={{width:'40%', color: '#eee'}} onClick={this.handleHideAddress} class={`${s.errorbtn} ${s.errorbtnfirst}`}>返回</button>
													</div>
												</div>
											</div>
									}
									<br /><br />
								</div> :
									<div class="al-c">
										<h4 class="al-c pdt6 pdb2 white">
											{losingPrize.text}
										</h4>
										<div className={s.prize} style={{'background-image': `url(${losingPrize.img})`}}>&nbsp;</div>
									</div>}
							</div> : null
					}
					<Modal isOpen={!!this.state.error.error} onRequestClose={this.closeErr}>
						<div className={s.error}>
							<h3>{this.state.error.title}</h3>
							{this.state.error.error}
							{
								this.state.error.title === '温馨提示' ?
									<div className={s.mbtn}>
										<button onClick={this.handleXianchang} class={`${s.errorbtn} ${s.errorbtnfirst}`}>填写</button>
									</div> : null
							}
							{
								this.state.error.title === '' || this.state.error.title === '保存成功' ?
									<div className={s.mbtn}>
										<button onClick={this.closeErr} class={`${s.errorbtn} ${s.errorbtnfirst}`}>确定</button>
									</div> : null
							}
						</div>
					</Modal>
				</div>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return state;
}


function mapDispatchToProps(dispatch){
	return bindActionCreators({ setStore: setRuntimeVariable}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Luck);
